/**
 * 测试日报功能脚本
 * 用于测试监控系统的24小时汇总报告功能
 */

require('dotenv').config();
const path = require('path');

// 设置工作目录到项目根目录
const projectRoot = path.join(__dirname, '..');
process.chdir(projectRoot);

const SummaryService = require(path.join(projectRoot, 'src/services/summaryService'));
const EmailService = require(path.join(projectRoot, 'src/services/emailService'));
const storage = require(path.join(projectRoot, 'src/utils/storage'));
const logger = require(path.join(projectRoot, 'src/utils/logger'));

async function testDailySummary() {
  logger.info('🧪 开始测试日报功能...');
  
  try {
    // 1. 测试生成汇总报告
    logger.info('📊 测试生成汇总报告...');
    const summaryService = new SummaryService();
    const summary = summaryService.generate24HoursSummary();
    
    logger.info('✅ 汇总报告生成成功');
    logger.info(`   - 总检查次数: ${summary.totalChecks}`);
    logger.info(`   - 成功检查: ${summary.successfulChecks}`);
    logger.info(`   - 新增交易对: ${summary.newPairsFound}`);
    logger.info(`   - 成功率: ${summary.successRate}%`);

    // 2. 创建测试数据
    logger.info('🔧 创建测试监控数据...');
    const testLogEntries = [
      {
        timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), // 2小时前
        totalPairs: 245,
        newPairs: ['KRW-TEST1'],
        success: true,
        error: null,
        checkDuration: 1234
      },
      {
        timestamp: new Date(Date.now() - 1 * 60 * 60 * 1000).toISOString(), // 1小时前
        totalPairs: 246,
        newPairs: ['KRW-TEST2', 'BTC-TEST1'],
        success: true,
        error: null,
        checkDuration: 2345
      },
      {
        timestamp: new Date(Date.now() - 30 * 60 * 1000).toISOString(), // 30分钟前
        totalPairs: 248,
        newPairs: [],
        success: false,
        error: '网络连接超时',
        checkDuration: 5000
      },
      {
        timestamp: new Date().toISOString(), // 现在
        totalPairs: 248,
        newPairs: [],
        success: true,
        error: null,
        checkDuration: 1567
      }
    ];

    // 添加测试数据
    testLogEntries.forEach(entry => {
      storage.logMonitorActivity(entry);
    });
    
    logger.success('✅ 测试数据已添加');

    // 3. 重新生成汇总报告
    logger.info('📊 重新生成汇总报告（包含测试数据）...');
    const newSummary = summaryService.generate24HoursSummary();
    
    logger.info('✅ 新汇总报告生成成功');
    logger.info(`   - 总检查次数: ${newSummary.totalChecks}`);
    logger.info(`   - 成功检查: ${newSummary.successfulChecks}`);
    logger.info(`   - 失败检查: ${newSummary.failedChecks}`);
    logger.info(`   - 新增交易对: ${newSummary.newPairsFound}`);
    logger.info(`   - 独特新交易对: ${newSummary.uniqueNewPairs.join(', ')}`);
    logger.info(`   - 成功率: ${newSummary.successRate}%`);

    // 4. 测试邮件发送（如果配置了邮件）
    logger.info('📧 测试日报邮件发送...');
    const emailService = new EmailService();
    
    // 检查邮件配置
    const emailConfigured = await emailService.verifyConfig();
    
    if (emailConfigured) {
      logger.info('📤 邮件配置正常，开始发送测试日报...');
      const emailSent = await emailService.sendDailySummaryEmail();
      
      if (emailSent) {
        logger.success('✅ 测试日报邮件发送成功！');
      } else {
        logger.error('❌ 测试日报邮件发送失败');
      }
    } else {
      logger.warn('⚠️  邮件未配置，跳过邮件发送测试');
      logger.info('💡 要测试邮件功能，请配置 .env 文件中的邮件设置');
    }

    // 5. 显示生成的HTML和文本内容预览
    logger.info('📝 生成的邮件内容预览:');
    console.log('\n=== 邮件主题 ===');
    console.log(`📊 Upbit监控日报 - ${new Date().toLocaleDateString('zh-CN')} - ${emailService.getSummaryStatusEmoji(newSummary.successRate)}`);
    
    console.log('\n=== 文本内容预览 ===');
    const textContent = summaryService.generateEmailText(newSummary);
    console.log(textContent.substring(0, 500) + '...\n');

    logger.success('🎉 日报功能测试完成！');
    
  } catch (error) {
    logger.error(`测试过程中出错: ${error.message}`);
    logger.error(error.stack);
  }
}

// 运行测试
testDailySummary().then(() => {
  logger.info('👋 测试脚本执行完成');
  process.exit(0);
}).catch(error => {
  logger.error(`测试脚本执行失败: ${error.message}`);
  process.exit(1);
});
